<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_file");
\ns_core\m_load::load("ns_core.m_mediainfo");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load_old("nn_logic/message/nl_message.class.php");
\ns_core\m_load::load_np("np_xml2array.class.php");
$arr_dir = explode('|', str_replace(array('/', '\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('ORG_ID', $str_dir);

//soap注入公共入口
class import extends \ns_model\message\message_queue
{
    public $ftp_url = 'ftp://tbjy:tbjy@172.26.2.17:21/';
//     public $ftp_url='ftp://ftp_user:ftp_user@192.168.70.55:21/temp_oms_shidake/';
    public $ftp_pasv = true;

    public $base_dir = '/tbjy';
    public $ftp_dir = '';
    public $error_data = array();
    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info' => array(
            'nns_message_time' => '', //上游消息时间  年月日时分秒毫秒
            'nns_message_id' => '',  //上游消息ID
            'nns_cp_id' => '', //上游CP标示
            'nns_message_xml' => '',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content' => '',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action' => '', //操作 行为
            'nns_type' => '', //消息 类型
            'nns_name' => '',  //消息名称
            'nns_package_id' => '',  //包ID
            'nns_xmlurlqc' => '', //广州电信悦ME MD5摘要
            'nns_encrypt' => '', //广州电信悦ME 加密串
            'nns_content_number' => '', //xml文件中包含的内容数量
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        m_config::get_dc();
        m_config::base_write_log('message', 'request', "-----------消息接收开始-----------", m_config::return_child_path(__FILE__));
    }

    public function init()
    {
        m_file::$ex_file_name = 'ts';
        $result_files = m_file::get_files_v2($this->base_dir . '/' . ORG_ID);

        if (empty($result_files) || !is_array($result_files)) {
            return m_config::return_data(1, '未获取到文件列表数据');
        }
        $last_data = null;

        foreach ($result_files as $key => $value) {
            //获取集号,按照片源数字部分取
            $path_info = array();
            $path_info = pathinfo($value['path']);

            if( empty($path_info['extension']) ){
                continue;
            }

            if (preg_match('/\/多集\//', $value['path'])) {
                //多集则获取ts文件名中的数字部分作为集数
                preg_match('/(\d+)/',$path_info['filename'],$match);
                $value['nns_index_sequence'] =isset($match[1])?(int)$match[1]:0;
            }else{
                //单集  sequence=0
                $value['nns_index_sequence'] = 0;
            }

            //获取主媒资名称
            $arr_path = explode('|', str_replace(array('/', '\\'), '|', $value['path']));
            array_pop($arr_path);
            $video_name = array_pop($arr_path);

            //主媒资,分集,片源nns_id
            $value['nns_video_nane'] = $video_name;
            $value['nns_id_video'] = md5($video_name);
            $value['nns_id_index'] = md5($value['path'] . '_index');
            $value['nns_id_media'] = md5($value['path']);

            //message_id
            $value['nns_message_id'] = md5($value['path']);
            $last_data[$key] = $value;
        }

        // unset($result_files);
        $ftp_ts = trim(rtrim(rtrim($this->ftp_url, '/'), '\\'));

        foreach ($last_data as $last_value) {
            $base_url = $last_value['path'];
            $last_value['path'] = str_replace($this->base_dir, '', $last_value['path']);
            $arr_pathinfo = pathinfo($last_value['path']);
            $file_name = isset($arr_pathinfo['filename']) ? trim($arr_pathinfo['filename']) : '';
            $file_name = trim(str_replace('（视达科专用）', '', str_replace('HD', '', $file_name)));

            if (strlen($file_name) < 1) {
                continue;
            }

            $result_exsist = nl_message::query_by_condition(m_config::get_dc(), array('nns_cp_id' => ORG_ID, 'nns_message_id' => $last_value['nns_message_id']));
            if ($result_exsist['ret'] != 0) {
                return $result_exsist;
            }

            if (isset($result_exsist['data_info']) && is_array($result_exsist['data_info']) && !empty($result_exsist['data_info'])) {
                continue;
            }

            $media_info_guid = 'temp/mediainfo/temp/' . np_guid_rand() . '.xml';
            $result_make_dir = m_config::make_dir($media_info_guid);
            if ($result_make_dir['ret'] != 0) {
                return $result_make_dir;
            }
            $result_mediainfo = m_mediainfo::exec_ftp($ftp_ts . '/' . trim(ltrim(ltrim($last_value['path'], '/'), '\\')), $result_make_dir['data_info']['absolute_dir']);
            $arr_media_info = null;
            if ($result_mediainfo['ret'] == '0' && strlen($result_mediainfo['data_info']) > 0 && m_config::is_xml($result_mediainfo['data_info'])) {
                $arr_media_info = simplexml_load_string($result_mediainfo['data_info']);
                $arr_media_info = json_decode(json_encode($arr_media_info), true);
            }
            $int_bit_rate = isset($arr_media_info['File']['track'][0]['Overall_bit_rate'][0]) ? (int)$arr_media_info['File']['track'][0]['Overall_bit_rate'][0] : 10 * 1024 * 1024;
            $int_bit_rate = floor($int_bit_rate);
            $media_formart = isset($arr_media_info['File']['track'][0]['Overall_bit_rate_mode'][0]) ? $arr_media_info['File']['track'][0]['Overall_bit_rate_mode'][0] : '';

            $media_formart = is_string($media_formart) ? strtolower($media_formart) : '';
//             if(strtoupper($media_formart) !='VBR')
//             {
//                 $this->error_data[] = $last_value;
//                 continue;
//             }
            $nns_file_size = isset($arr_media_info['File']['track'][0]['File_size'][0]) ? (int)$arr_media_info['File']['track'][0]['File_size'][0] / 1024 : 38406125 / 1024;
            $nns_file_size = floor($nns_file_size);
            $FrameHeight = (isset($arr_media_info['File']['track'][1]['Sampled_Height']) && (int)$arr_media_info['File']['track'][1]['Sampled_Height'] > 0) ? (int)$arr_media_info['File']['track'][1]['Sampled_Height'] : 1080;
            $FrameWidth = (isset($arr_media_info['File']['track'][1]['Sampled_Width']) && (int)$arr_media_info['File']['track'][1]['Sampled_Width'] > 0) ? (int)$arr_media_info['File']['track'][1]['Sampled_Width'] : 1920;

            $nns_resolution = $FrameWidth . '*' . $FrameHeight;
            $nns_file_len = isset($arr_media_info['File']['track'][0]['Duration'][0]) ? ((int)$arr_media_info['File']['track'][0]['Duration'][0] / 1000) : 10 * 60;
            $nns_file_len = floor($nns_file_len);

            $asset_info = array(
                'video' => array(
                    'nns_id' => $last_value['nns_id_video'],
                    'nns_name' => $file_name,
                    'nns_cp_id' => ORG_ID,
                    'nns_file_len' => $nns_file_len,
                ),
                'index' => array(
                    'nns_id' => $last_value['nns_id_index'],
                    'nns_name' => $file_name,
                    'nns_cp_id' => ORG_ID,
                    'nns_file_len' => $nns_file_len,
                    'nns_index_sequence' => $last_value['nns_index_sequence']
                ),
                'media' => array(
                    'nns_id' => $last_value['nns_id_media'],
                    'nns_url' => $ftp_ts . '/' . trim(ltrim(ltrim($last_value['path'], '/'), '\\')),
                    'nns_cp_id' => ORG_ID,
                    'nns_screenformat' => 0,
                    'nns_file_size' => $nns_file_size,
                    'nns_bitrate' => $int_bit_rate,
                    'nns_resolution' => $nns_resolution,
                ),
            );
            $nns_message_content = $this->make_model($asset_info, '文件扫描', 1);

            $this->import($last_value['nns_message_id'], $ftp_ts . '/' . trim(ltrim(ltrim($last_value['path'], '/'), '\\')), $nns_message_content);
        }
        return m_config::return_data(0, '获取到文件列表数据', $result_files);
    }

    /**
     * 注入
     * @return multitype:number |string
     */
    public function import($message_id, $ftp_ts, $nns_message_content)
    {
        $this->ContentMngXMLURL = $ftp_ts;
        $this->setFuse_enabled(false);
        $this->arr_in_message['base_info']['nns_message_xml'] = $this->ContentMngXMLURL;
        $this->arr_in_message['base_info']['nns_message_id'] = $message_id;
        $this->arr_in_message['base_info']['nns_message_time'] = date("YmdHis");
        $this->arr_in_message['base_info']['nns_cp_id'] = ORG_ID;
        $nns_message_content = trim($nns_message_content);
        if (strlen($nns_message_content) < 1) {
            $this->arr_in_message['base_info']['nns_message_state'] = '1';
            $this->arr_in_message['base_info']['nns_message_content'] = "获取内容为空地址:[{$this->ContentMngXMLURL}]";
            return $this->message_action('add', $this->arr_in_message);
        }
        if (!m_config::is_xml($nns_message_content)) {
            $this->arr_in_message['base_info']['nns_message_state'] = '2';
            $this->arr_in_message['base_info']['nns_message_content'] = "非xml内容:[{$nns_message_content}]";
            $this->arr_in_message['base_info']['nns_message_content'] = $nns_message_content;
            return $this->push($this->arr_in_message);
        }
        $this->exec_ex_data($nns_message_content);
        #TODO  这儿依据不同内容做解析
        $this->arr_in_message['base_info']['nns_message_content'] = $nns_message_content;
        return $this->push($this->arr_in_message);
    }


    /**
     * 处理扩展数据
     * @param unknown $nns_message_content
     */
    public function exec_ex_data($nns_message_content)
    {
        $int_action = $int_type = 1;
        $nns_message_content = m_config::trim_xml_header($nns_message_content);
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($nns_message_content);
        $xml = $dom->saveXML();
        $xml_arr = np_xml2array::getArrayData($xml);
        $Objects = null;
        if (isset($xml_arr['data']['children']) && is_array($xml_arr['data']['children']) && !empty($xml_arr['data']['children'])) {
            foreach ($xml_arr['data']['children'] as $v) {
                if (empty($Objects) && $v['name'] == 'Objects') {
                    $Objects = $v['children'];
                }
            }
        }
        if (!empty($Objects) && is_array($Objects)) {
            foreach ($Objects as $obj) {
                $int_action = (isset($obj['attributes']['Action']) && strtoupper($obj['attributes']['Action']) == 'DELETE') ? 3 : ((isset($obj['attributes']['Action']) && strtoupper($obj['attributes']['Action']) == 'UPDATE') ? 2 : 1);

                //分集
                if ($obj['attributes']['ElementType'] == 'Program') {
                    $int_type = 2;
                } //片源
                else if ($obj['attributes']['ElementType'] == 'Movie') {
                    $int_type = 3;
                } //直播频道
                else if ($obj['attributes']['ElementType'] == 'Channel') {
                    $int_type = 4;
                } //直播片源
                else if ($obj['attributes']['ElementType'] == 'PhysicalChannel') {
                    $int_type = 6;
                } //节目单
                else if ($obj['attributes']['ElementType'] == 'ScheduleRecord') {
                    $int_type = 7;
                }
            }
        }
        $this->arr_in_message['base_info']['nns_action'] = $int_action;
        $this->arr_in_message['base_info']['nns_type'] = $int_type;
        return;
    }

    /**
     * 生成主媒资、分集、片源（针对电影）
     * @param unknown $asset_info
     * @param unknown $cate_name
     * @param unknown $media_mode
     * @param string $str_tag
     * @param number $SystemLayer
     */
    public function make_model($asset_info, $cate_name, $media_mode, $str_tag = '26,', $SystemLayer = 1)
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        $xml .= '<Objects>';
        $xml .= '<Object ElementType="Series" ContentID="' . $asset_info['video']['nns_id'] . '" Action="REGIST" Code="' . $asset_info['video']['nns_id'] . '">';
        $xml .= '<Property Name="Name"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="OrderNumber"/>';
        $xml .= '<Property Name="OriginalName"/>';
        $xml .= '<Property Name="AliasName"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="EnglishName"/>';
        $xml .= '<Property Name="SortName"/>';
        $xml .= '<Property Name="SearchName"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml .= '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml .= '<Property Name="LicensingWindowStart"/>';
        $xml .= '<Property Name="LicensingWindowEnd"/>';
        $xml .= '<Property Name="CPContentID"><![CDATA[' . $asset_info['video']['nns_cp_id'] . ']]></Property>';
        $xml .= '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Price"/>';
        $xml .= '<Property Name="VolumnCount"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="NewCount"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Description"><![CDATA[]]></Property>';
        $xml .= '<Property Name="ContentProvider"><![CDATA[' . $asset_info['video']['nns_cp_id'] . ']]></Property>';
        $xml .= '<Property Name="KeyWords"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml .= '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml .= '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml .= '<Property Name="Language"><![CDATA[]]></Property>';
        $xml .= '<Property Name="Kind"><![CDATA[]]></Property>';
        $xml .= '<Property Name="ViewType"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Duration"><![CDATA[' . $asset_info['video']['nns_file_len'] . ']]></Property>';
        $xml .= '<Property Name="CategoryName"><![CDATA[' . $cate_name . ']]></Property>';
        $xml .= '<Property Name="CategoryID"/>';
        $xml .= '<Property Name="PlayCount"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="CategorySort"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Tags"><![CDATA[' . $str_tag . ']]></Property>';
        $xml .= '<Property Name="ViewPoint"/>';
        $xml .= '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml .= '<Property Name="Rating"/>';
        $xml .= '<Property Name="Awards"/>';
        $xml .= '<Property Name="Sort"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Reserve1"/>';
        $xml .= '<Property Name="Reserve2"/>';
        $xml .= '</Object>';
        $xml .= '<Object ElementType="Program" ContentID="' . $asset_info['index']['nns_id'] . '" Action="REGIST" Code="' . $asset_info['index']['nns_id'] . '">';
        $xml .= '<Property Name="Name"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="CPContentID"><![CDATA[' . $asset_info['video']['nns_cp_id'] . ']]></Property>';
        $xml .= '<Property Name="OrderNumber"/>';
        $xml .= '<Property Name="OriginalName"/>';
        $xml .= '<Property Name="Sequence"><![CDATA[' . $asset_info['index']['nns_index_sequence'] . ']]></Property>';
        $xml .= '<Property Name="SortName"/>';
        $xml .= '<Property Name="SearchName"/>';
        $xml .= '<Property Name="OriginalCountry"><![CDATA[]]></Property>';
        $xml .= '<Property Name="ActorDisplay"><![CDATA[]]></Property>';
        $xml .= '<Property Name="WriterDisplay"><![CDATA[]]></Property>';
        $xml .= '<Property Name="Language"><![CDATA[]]></Property>';
        $xml .= '<Property Name="OrgAirDate"><![CDATA[2012-05-05]]></Property>';
        $xml .= '<Property Name="ReleaseYear"><![CDATA[2012-05-05]]></Property>';
        $xml .= '<Property Name="LicensingWindowStart"/>';
        $xml .= '<Property Name="LicensingWindowEnd"/>';
        $xml .= '<Property Name="DisplayAsNew"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="DisplayAsLastChance"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Macrovision"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Description"><![CDATA[]]></Property>';
        $xml .= '<Property Name="PriceTaxIn"/>';
        $xml .= '<Property Name="Status"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="SourceType"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="SeriesFlag"/>';
        $xml .= '<Property Name="ContentProvider"><![CDATA[' . $asset_info['video']['nns_cp_id'] . ']]></Property>';
        $xml .= '<Property Name="KeyWords"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="Tags"><![CDATA[' . $str_tag . ']]></Property>';
        $xml .= '<Property Name="ViewPoint"/>';
        $xml .= '<Property Name="StarLevel"><![CDATA[6]]></Property>';
        $xml .= '<Property Name="Rating"/>';
        $xml .= '<Property Name="Awards"/>';
        $xml .= '<Property Name="Duration"><![CDATA[' . $asset_info['video']['nns_file_len'] . ']]></Property>';
        $xml .= '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="Reserve1"/>';
        $xml .= '<Property Name="Reserve2"/>';
        $xml .= '<Property Name="Reserve3"/>';
        $xml .= '<Property Name="Reserve4"/>';
        $xml .= '<Property Name="Reserve5"/>';
        $xml .= '</Object>';
        $xml .= '<Object ElementType="Movie" ContentID="' . $asset_info['media']['nns_id'] . '" Action="REGIST" Code="' . $asset_info['media']['nns_id'] . '">';
        $xml .= '<Property Name="Type"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="FileURL"><![CDATA[' . $asset_info['media']['nns_url'] . ']]></Property>';
        $xml .= '<Property Name="CPContentID"><![CDATA[' . $asset_info['video']['nns_cp_id'] . ']]></Property>';
        $xml .= '<Property Name="Name"><![CDATA[' . $asset_info['video']['nns_name'] . ']]></Property>';
        $xml .= '<Property Name="SourceDRMType"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="DestDRMType"><![CDATA[0]]></Property>';
        $xml .= '<Property Name="AudioType"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="ScreenFormat"><![CDATA[' . $asset_info['media']['nns_screenformat'] . ']]></Property>';
        $xml .= '<Property Name="ClosedCaptioning"><![CDATA[1]]></Property>';
        $xml .= '<Property Name="Tags"><![CDATA[' . $str_tag . ']]></Property>';
        $xml .= '<Property Name="Duration"><![CDATA[' . $asset_info['video']['nns_file_len'] . ']]></Property>';
        $xml .= '<Property Name="FileSize"><![CDATA[' . $asset_info['media']['nns_file_size'] . ']]></Property>';
        $xml .= '<Property Name="BitRateType"><![CDATA[' . $asset_info['media']['nns_bitrate'] . ']]></Property>';
        $xml .= '<Property Name="VideoType"/>';
        $xml .= '<Property Name="AudioEncodingType"><![CDATA[4]]></Property>';
        $xml .= '<Property Name="Resolution"><![CDATA[' . $asset_info['media']['nns_resolution'] . ']]></Property>';
        $xml .= '<Property Name="MediaMode"><![CDATA[' . $media_mode . ']]></Property>';
        $xml .= '<Property Name="SystemLayer"><![CDATA[' . $SystemLayer . ']]></Property>';
        $xml .= '<Property Name="ServiceType"><![CDATA[HTTP]]></Property>';
        $xml .= '<Property Name="Domain"/>';
        $xml .= '<Property Name="Hotdegree"><![CDATA[0]]></Property>';
        $xml .= '</Object>';
        $xml .= '</Objects>';
        $xml .= '<Mappings>';
        $xml .= '<Mapping ParentType="Series" ParentID="' . $asset_info['video']['nns_id'] . '" ElementType="Program" ElementID="' . $asset_info['index']['nns_id'] . '" ParentCode="' . $asset_info['video']['nns_id'] . '" ElementCode="' . $asset_info['index']['nns_id'] . '" Action="REGIST"/>';
        $xml .= '<Mapping ParentType="Program" ParentID="' . $asset_info['index']['nns_id'] . '" ElementType="Movie" ElementID="' . $asset_info['media']['nns_id'] . '" ParentCode="' . $asset_info['index']['nns_id'] . '" ElementCode="' . $asset_info['media']['nns_id'] . '" Action="REGIST"/>';
        $xml .= '</Mappings>';
        $xml .= '</ADI>';
        return $xml;
    }

    /**
     * 类销毁
     */
    public function __destruct()
    {
        m_config::base_write_log('message', 'request', "-----------消息接收结束-----------", m_config::return_child_path(__FILE__));
    }
}

$delivery_import = new import();
$result = $delivery_import->init();
echo json_encode($delivery_import->error_data);